/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    contact:dcdev_founder@foxmail.com
*/
url = "https://www.layuicdn.com/layui/css/layui.css";
_link = document.createElement("link");
_link.type = "text/" + ("css");
_link.rel = "stylesheet";
_link.href = url;
_head = document.getElementsByTagName('head')[0];
_head.insertBefore(_link, _head.lastChild)

// 引入styls
style = `.layui-form-label{text-align:left;}.layui-form-label::before{content:'';width:0;height:26px;border-left:3px solid #1296db;position:absolute;left:0;top:6px;}`
_style = document.createElement("style");
_style.type = "text/css";
try {
    _style.appendChild(document.createTextNode(style));
} catch (ex) {
    _style.styleSheet.cssText = style;//针对IE
}
_head = document.getElementsByTagName("head")[0];
_head.appendChild(_style);

var offset_x;
var offset_y;

function popupForm(set, config = null) {
    // 为空时使用默认配置
    if (!config) {
        config = {};
        if (browser_info.is_mobile) {
            config.width = "92%", config.height = "92%";
        }
        else {
            config.width = "80%", config.height = "70%";
        }
    }
    // 有配置，但要确定是否有该值
    else {
        if (!config.width) {
            if (browser_info.is_mobile) {
                config.width = "92%";
            }
            else {
                config.width = "80%";
            }
        }

        if (!config.height) {
            if (browser_info.is_mobile) {
                config.height = "92%";
            }
            else {
                config.height = "70%";
            }
        }
    }
    if (set.margin) {
        set.area = [];
        for (var i = 0; i < set.margin.length; i++) {
            if (i == 0) {
                set.area.push(($(parent.window).width() - parseInt(set.margin[i]) * 2) + 'px')
            } else {
                set.area.push(($(parent.window).height() - parseInt(set.margin[i]) * 2) + 'px')
            }
        }
        delete set.margin;
    }
    var obj = {
        type: 1
        , title: false //不显示标题栏
        , closeBtn: false
        , area: [config.width, config.height] //宽高
        , offset: 'auto'   //定位
        , scrollbar: false
        , shade: 0.001  //蒙层
        , id: 'LAY_layuipro' //设定一个id，防止重复弹出
        , btn: [config.config_button ? config.config_button : '确定', config.cancel_button ? config.cancel_button : '取消']
        , btnAlign: 'c'  //按钮居中
        , moveType: 1 //拖拽模式，0或者1
    }
    Object.assign(obj, set)
    layui.use('layer', function () {
        var layer = layui.layer;
        parent.layer.open(obj)
    })
}

function open(data, cb) {
    // 调整窗体宽高
    {
        if (browser_info.is_mobile) {
            w = data.appear.mobile.size.w;
            h = data.appear.mobile.size.h;
            // 如果是百分比
            if (data.appear.mobile.size.w.charAt((data.appear.mobile.size.w).length - 1) == "%") {
                w = parseInt(w.substr(0, w.length - 1))
                w = (window.screen.width * w) / 100 + "px"
            }
            if (data.appear.mobile.size.h.charAt((data.appear.mobile.size.h).length - 1) == "%") {
                h = parseInt(h.substr(0, h.length - 1))
                h = (window.screen.height * h) / 100 + "px"
            }
            offset_y = "10px"
        } else {
            w = data.appear.pc.size.w;
            h = data.appear.pc.size.h;
            // 如果是百分比
            if (data.appear.pc.size.w.charAt((data.appear.pc.size.w).length - 1) == "%") {
                w = parseInt(w.substr(0, w.length - 1))
                w = window.screen.width * w / 100 + "px"
            }
            if (data.appear.pc.size.h.charAt((data.appear.pc.size.h).length - 1) == "%") {
                h = parseInt(h.substr(0, h.length - 1))
                h = window.screen.height * h / 100 + "px"
            }
        }
    }

    var form_config = {
        area: [w, h],
        id: 'dcdev-popup-form',
        yes: function (index, layero) {
            if (parent.$('input[name="input_field"]').val().length <= 0) {
                return;
            }
            parent.layer.close(index)
        },
        shade: data.mask,
        btn2: function () { },
        content: '<div id="input_field" style="padding: 10px; line-height: 22px;  font-weight: 300;"></div><div class="layui-layer-btn" style="text-align:center;"><a class="layui-layer-btn0 surebtn">确定</a><a class="layui-layer-btn1">取消</a></div>',
        success: function (layero) {
            parent.$('.layui-layer-btn-c').remove()
            // 有偏移值
            if (offset_y)
                parent.$('#dcdev-popup-form').parent().css('top', offset_y)

            parent.$('#input_field').append(`<label style="content:'';width:90%;left: 0;color:#000;" 
            class='dcdev-title'>${data.title}</label>`)
            var html;
            parent.$('#dcdev-popup-form').css('height', h)
            html = '<input name="input_field" type="text" maxlength="' + data.maxNum + '" placeholder="' + data.placeholder +
                '" class="layui-input" /><div class="dcdev-text01 layui-input-block inputmsg"></div>';
            parent.$('#input_field').append(html)
            $(".historyTitle_td").click(function () {
                parent.$("input[name='input_field']").val($(this).text());
            })
            parent.$('.layui-layer-btn0').click(function () {
                cb({ res: 1, text: parent.$('input[name="input_field"]').val(), length: (parent.$('input[name="input_field"]').val()).length })
            })
            parent.$("input[name='input_field']").focus();
            parent.$('.inputmsg').css("padding-left", "0px").css("margin-left", "10px");

            parent.$(`input[name="input_field"]`).bind('input', inputVerify)
            parent.$('.inputmsg').html(`长度必须介于${data.minNum}与${data.maxNum}之间`).css('color', '#FF5722');
            parent.$("input[name='input_field']").val(data.text.length > data.maxNum ? data.text.substr(0, 3) : data.text);
            //按钮样式
            if (parent.$('input[name="input_field"]').val().length <= 0) {
                parent.$('.surebtn').addClass('layui-btn-disabled').removeClass('layui-layer-btn0').css({
                    'background-color': '#dedede',
                    'color': '#fff'
                })
            } else {
                parent.$('.layui-layer-btn0').removeClass('layui-btn-disabled').addClass('layui-layer-btn0').css({
                    'background-color': '',
                    'color': ''
                })
            }

            if (browser_info.is_andriod) {
                //获取原窗口的高度
                var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
                window.onresize = function () {
                    //键盘弹起与隐藏都会引起窗口的高度发生变化
                    var resizeHeight = document.documentElement.clientHeight || document.body
                        .clientHeight;
                    if (resizeHeight - 0 >= originalHeight - 0) {
                        document.body.scrollTop = $(document).height() - $(document).scrollTop();
                    }
                }
            }
            if (browser_info.is_ios) {
                parent.document.body.addEventListener('focusout', function () { //软键盘关闭事件
                    parent.document.body.scrollTop = parent.$(document).height() - parent.$(
                        document).scrollTop();
                });
            }
        },
        end: function () {

        }
    }

    // 根据配置弹出页面
    popupForm(form_config);
    //软键盘弹出的事件处理
    $(document).on('focusin', function () {
        parent.$("#dcdev-popup-form").css("height");
    });

    //软键盘收起的事件处理
    $(document).on('focusout', function () {
        parent.$("#dcdev-popup-form").css("height");
    });
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    $(window).on('resize', function () {
        var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        if (clientHeight > nowClientHeight) {
            //键盘弹出的事件处理
            parent.$("#dcdev-popup-form").css("height", h);
        }
        else {
            // //键盘收起的事件处理
            parent.$("#dcdev-popup-form").css("height", h);
        }
    });

    //监听手机屏幕翻转
    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", handleRotage, false);

    function handleRotage() {
        if (window.orientation == 90 || window.orientation == -90) {
            if (parent.$("#dcdev-popup-form").length >= 1) {
                popupForm(form_config);
            }
        } else if (window.orientation == 0) {
            if (parent.$("#dcdev-popup-form").length >= 1) {
                popupForm(form_config);
            }
        }
        // 有偏移值
        if (offset_y)
            parent.$('#dcdev-popup-form').parent().css('top', offset_y)

    }

    // 验证输入内容
    function inputVerify(el = null, input) {
        if (input) {
            var _this = $(input);
        } else {
            var _this = $(this);
        }
        setTimeout(function () {
            //去除空格
            var val = _this.val();
            var len = val.length;
            if (len < data.minNum) {
                $('.inputmsg').html(`长度必须介于${data.minNum}与${data.maxNum}之间`).css('color', '#FF5722');
                parent.$('.surebtn').addClass('layui-btn-disabled').removeClass('layui-layer-btn0').css({
                    'background-color': '#dedede',
                    'color': '#fff'
                })
                if (!$(`.input_field`).hasClass('red-label')) {
                    $(`.input_field`).addClass('red-label')
                }
                disabled = true
            } else {
                parent.$('.surebtn').removeClass('layui-btn-disabled').addClass('layui-layer-btn0').css({
                    'background-color': '',
                    'color': ''
                })
                $('.inputmsg').html(`${len}/${data.maxNum}`).css('color', 'rgb(153,153,153)')
                if ($(`.input_field`).hasClass('red-label')) {
                    $(`.input_field`).removeClass('red-label')
                }
                disabled = false
            }
        }, 0)
    }
}
